(function() {

return;	// disable script

// ----------------------------------------------

var THROTTLE_INTERVAL = 1;	// in seconds;

// ----------------------------------------------
var playerTSID;
var total = 0;
var scraped = 0, scrapeCount = 0;
var checked = 0, checkCount = 0;

$(document).ready(function() {
	if (!playerTSID) {
		api_call('players.info', {}, function(e) {
			if (e.ok) { playerTSID = e.player_tsid;	}
		});
	}	
	initUI();
	hookupHotkeys();

	$.ajax({ url: LISTING_SCRIPT, dataType: "script"
		, error: function() { 
			if (typeof(locations) === 'undefined') { 
				$("#status").text("Oops! The hamsters have gone amok. Please reload!"); return; 
			} 
		}
		, success: function(data, textStatus) {

			// If we're going to add streets into their proper lists, we ought to label each region's list
			$("h3").each(function () {
				var name = $(this).html().replace(/\s+/g, "").toLowerCase();
				$(this).next().attr("id", name);
			});

			// Create a temporary place to put new streets
			var TEMP_REGIONS = {
//					'xalanga': { 'name': 'Xalanga', 'after': 'zhambu'}
//					,'salatu': { 'name': 'Salatu', 'after': 'xalanga'}
//					,'muufo': { 'name': 'Muufo', 'after': 'salatu'}
			};
			for (regionSlug in TEMP_REGIONS) {
				region = TEMP_REGIONS[regionSlug];
				if ($('#' + regionSlug).length == 0) {
					$('#' + region.after).parent().after('<div class="section label-section"><h3>' + region.name + '</h3><ul class="list" id="' + regionSlug + '" style="margin: -20px 0;"></ul>');
				}
			}

			hookupRegionActions();

			var listed = [];
			$('ul.list a').each(function() {
				listed.push($(this).attr("href").split("/")[2]);
			});

			var sortIndex = {};

			// Loop through locations and add links.                
			for (tsid in locations) {
				// Only add a link if the street hasn't already been listed already.
				var region = locations[tsid].region;
				if (listed.indexOf(tsid) == -1){
					var regionEl = ($("#" + region).length > 0) ? $("#" + region) : $("#other");
					var sortname = (locations[tsid].sortname ? 'sortname="' + locations[tsid].sortname + '"' : '');
					var newItem = $('<li><a ' + sortname + ' href="/locations/' + tsid + '/">'+locations[tsid].name+'</a></li>');

					// For readability, let's indent housing streets.
					if (locations[tsid].name.match(/block|model|towers|villa|loft|lofts|apartments|cottages|manor|subway station|machine/gi)) {
						if(locations[tsid].name.match(/subway station/gi)) {
							newItem.addClass("subway");
						}
						newItem.addClass("substreet indented");
					}

					// Insert the street in the list, where it should be alphabetically.
					var added = false;
					var name = (locations[tsid].sortname) ? locations[tsid].sortname : locations[tsid].name;

					$("li", regionEl).slice(sortIndex[region]).each(function(index){
						var listItem = $(this).children(":first");
						var listItemName = (listItem.attr('sortname') ? listItem.attr('sortname') : listItem.text());
						if (listItemName > name) {
							newItem.insertBefore($(this));
							if(sortIndex[region] == undefined)
								sortIndex[region] = 0;
							if(!locations[tsid].sortname)
								sortIndex[region] += index+1;
							added = true;
							return false;
						}
					});

					// And if it doesn't get added, just throw it on the end.
					if (!added) {
						newItem.appendTo(regionEl);
					}
				}
			}

			$("ul.list li").append("<span class='qty'></span><span class='after'></span>")

			hookupLocationLinks(locations);
		} // success
	});   // $.ajax

});

function initUI() {
	$("<style type='text/css'>"
		+ ".indented { margin-left: 36px !important; font-size: 12px; }"
		+ ".filter { text-align: right; margin-top: 5px; }"
		+ "#regions-list { width: 100%; line-height: 1.4em; font-size: 12px; }"
		+ "#regions-list a { margin-left: 8px; }"
		+ "a.disabledButton, a.disabledButton:hover { color: #BECCCC; border-color: #BECCCC; }"
		+ "a.currLocation { color: #fff; background-color: #005C73; padding: 2px 3px 2px 3px; border-radius: 2px; }"
		+ "a.unvisited { color: #005C73; font-weight: bold; }"
		+ "a.visited { color: darkgray; font-weight: normal; }"
		+ "div#shortcuts { color: #999; }"
		+ "</style>").appendTo("head");
	$('div.container').after('<div id="shortcuts">press: <b>h</b> to go to the top | <b>m</b> to show your current location | <b>j/k</b> to go to the next/previous region</div>');

	$('<div id="regions-list"><span>Regions:</span></div').insertAfter($('h1'));

	// Create a place to put odds and ends.
	$('.container').append('<div class="section label-section"><h3>Other</h3><ul id="other" class="list" style="margin: -20px 0;"></ul>');

} // function initUI()

function getOffset() {
	var scrollOffsetTop = 0;
	if (self.pageYOffset) {
		scrollOffsetTop = self.pageYOffset;
	} else {
		scrollOffsetTop = document.body.scrollTop;
	}
	//scrollOffsetTop += $(window).height();
	return scrollOffsetTop;
}

function hookupHotkeys() {

	$('html').keyup(function(e) {

		var keyPressed = String.fromCharCode(e.keyCode).toUpperCase();
		// Go up to top
		if (keyPressed === "H") {
			$('html, body').animate({scrollTop: 0 }, 'fast');
			return;
		}

		// Check player location
		if (keyPressed === "M") {
			if (!playerTSID) { return; }
			$('.label-section a.currLocation').removeClass('currLocation');
			api_call('players.fullInfo', { 'player_tsid': playerTSID }, function(e) {
				if (!e.ok) { console.error(e.error); }
				var loc = $('.label-section a[href="/locations/' + e.location.tsid + '/"]');
				if (loc && loc.length > 0) {
					var center = Math.round($(window).height()/2) - 10;
					var top = loc.offset().top;
					top = (top > center ? top - center : top);
					$('html, body').animate({scrollTop: top }, 'fast', function(e) {
						loc.addClass('currLocation');
					});
				}
			});
			return;
		}

		// Jump to next/previous region
		if (keyPressed === "J" || keyPressed === "K") {
			var offsetTop = getOffset();
			var regions = $('.label-section');
			regions.each(function(i, e) {
				var region = $(e);
				if ((region.offset().top < offsetTop && region.offset().top + region.height() > offsetTop)
					|| region.offset().top >= offsetTop
				) {
					if (keyPressed === "K" && i == 0) {	// got to top if at first region
						$('html, body').animate({scrollTop: 0 }, 'fast');
						return false;
					}
					var nextRegion = (keyPressed === "J" ? region.next() : region.prev());
					if (nextRegion && nextRegion.offset()) {
						$('html, body').animate({scrollTop: nextRegion.offset().top }, 'fast', function() { 
							nextRegion.find('.checkRes').focus(); 
						});
					}
					return false;
				}
			})
			return;
		}

		// Check visit for current region
		if (keyPressed === "1") {
			var offsetTop = getOffset();
			var regions = $('.label-section');
			regions.each(function(i, e) {
				var region = $(e);
				if ((region.offset().top < offsetTop && region.offset().top + region.height() > offsetTop)
					|| region.offset().top >= offsetTop
				) {
					$('html, body').animate({scrollTop: region.offset().top }, 'fast', function(e) {
						region.find('a.checkVisit').click();
					});
					return false;
				}
			})
			return;
		}

		// Check resource for current region
		if (keyPressed === "2") {
			var offsetTop = getOffset();
			var regions = $('.label-section');
			regions.each(function(i, e) {
				var region = $(e);
				if ((region.offset().top < offsetTop && region.offset().top + region.height() > offsetTop)
					|| region.offset().top >= offsetTop
				) {
					$('html, body').animate({scrollTop: region.offset().top }, 'fast', function(e) {
						region.find('a.checkRes').click();
					});
					return false;
				}
			})
			return;
		}
	});		// $('html').keyup(function(e)
}	// function hookupHotkeys()

function hookupRegionActions() {
	/*	-------------- FOR EACH REGION -------------- */
	$('div.section ul.list').each(function(i, e) {
		
		var list = $(e);
		if (list.attr('id') === 'other') { return; }

		var shortcutRegion = $('<a href="javascript: void(0);">' + list.prev('h3').html() + '</a>');
		shortcutRegion.click(function(e){
			$('html, body').animate({scrollTop: list.parent().offset().top }, 'fast');
		});
		$('#regions-list').append(shortcutRegion)

		var shortcutTop = $('<a title="Go back up! (or press \'h\')" style="font-size: 11px; margin-top: 5px; position: absolute; right: 5px; bottom: 10px; " href="javascript: void(0);">[ Top ]</a>');
		shortcutTop.click(function(e){
			$('html, body').animate({scrollTop: 0 }, 'fast');
		});
		list.after(shortcutTop)

		// Add shortcut link
		var checkButtons = $('<div id="buttons-' + list.attr('id') + '" style="position: absolute; top: 20px; right: 0px; font-size: 11px;"></div>');

		// Add Check Visit button
		var checkVisitLink = $('<a id="btnCheckVisit_' + list.attr('id') + '" title="Show visited status (visited: light grey, unvisited: bold)" href="javascript: void(0);" class="checkVisit button-tiny button-minor" region="' + list.attr('id') + '">Check Visits</a>');
		checkVisitLink.click(function(e) {
			var btn = $(this);
			var region = btn.attr('region');
			if (btn.attr('disabled')) { return; }
			
			$('.checkVisit, .checkRes').attr('disabled','disabled');
			btn.addClass('disabledButton');
			btn.html('Checking...');

			scraped = 0;
			scrapeCount = 0;
			
			var selector1 = '#' + region + ' li:not(.substreet) a';
			if ($(selector1 + '.visited').length > 0) {
				selector1 = selector1 + '.unvisited';
			}
			var selector2 = '#' + region + ' li.substreet a';
			if ($(selector2 + '.visited').length > 0) {
				selector2 = selector2 + '.unvisited';
			}
			total = $(selector1 + ' , ' + selector2).length;
			var combined = $.merge($(selector1), $(selector2));
			
			$.each(combined, function(index, element) {
				var href = window.location.protocol + '//' + window.location.host + $(this).attr("href");
				var link = $(this);
				//link.css("font-weight", "normal");
				//link.css("color", "#005C73");
				link.removeClass('visited').removeClass('unvisited');
				scrapeCount++;
				setTimeout(scrapePage, (index+1)*THROTTLE_INTERVAL*1000, [href, link, btn]);
			});
		});
		checkButtons.append(checkVisitLink);

		// Add Check Resources button
		var checkResLink = $('<a id="btnCheckRes_' + list.attr('id') + '" title="Refresh resource counts, e.g. trees, animals" href="javascript: void(0);" class="checkRes button-tiny button-minor" style="margin-left: 5px;" region="' + list.attr('id') + '" >Check Resources</a>');
		checkResLink.click(function(e){
			var btn = $(this);
			var region = btn.attr('region');
			if (btn.attr('disabled')) { return; }
			
			$('.checkVisit, .checkRes').attr('disabled','disabled');
			btn.addClass('disabledButton');
			btn.html('Checking...');
			$("#filter" + "-" + region + " select").attr("disabled","true");

			$("#" + region + " .qty").html("");
			$("#" + region + " li").show();
			$("#" + region + " .substreet").addClass("indented");

			checked = 0;
			checkCount = 0;
			total = $('#' + region + ' a').length;
			$('#' + region + ' a').each(function(index, element) {							
				var link = $(this);
				var appendage = link.parent().find(".after");
				
				// reset everything back to zero
				appendage.html('');
				var linkParent = link.parent();
				var isIndented = linkParent.hasClass('indented');
				var isSubstreet = linkParent.hasClass('substreet');
				var isSubway = linkParent.hasClass('subway');
				linkParent.removeClass();
				if (isIndented) { linkParent.addClass('indented'); }
				if (isSubstreet) { linkParent.addClass('substreet'); }
				if (isSubway) { linkParent.addClass('subway'); }
				$('#shrines-' + region + ', #vendors-' + region + ', #resources-' + region).children().remove()

				var tsid = link.attr("href").split("/")[2];
				checkCount++;
				setTimeout(getStreetInfo, (index+1)*THROTTLE_INTERVAL*1000, [tsid, link, appendage, index, btn, region]);
			});

		});
		checkButtons.append(checkResLink);

		// Add filter drop down
		var filterSelect = $("<select disabled='true' region='" + list.attr("id") + "'>" 
			+ "<option value='all' id='all-" + list.attr("id") + "'>All Streets</option>"
			+ "<option value='project' id='project-" + list.attr("id") + "'>Active Projects</option>"
			+ "<option value='subway' id='subway-" + list.attr("id") + "'>Subway Stations</option>" 
			+ "<optgroup label='Shrines' id='shrines-" + list.attr("id") + "'></optgroup>"
			+ "<optgroup label='Vendors' id='vendors-" + list.attr("id") + "'></optgroup>" 
			+ "<optgroup label='Resources' id='resources-" + list.attr("id") + "'></optgroup></select>");
		
		filterSelect.change(function(e) {
			var select = $(this);
			var region = select.attr("region");
			var val = select.val();
			$("#" + region + " .qty").html("");

			if(val == "all") {
				$("#" + region + " li").show();
				$("#" + region + " .substreet").addClass("indented");
				return;
			}

			$("#" + region + " .substreet").removeClass("indented");
			$("#" + region + " li." + val).show();
			$("#" + region + " li." + val + " a").each(function() {
				if($(this).attr(val)) {
					$(this).parent().find(".qty").html(" (" + $(this).attr(val) + ")");
				}
			});
			$("#" + region + " li:not(." + val +")").hide();
		});

		$("<div class='filter' id='filter-" + list.attr("id") + "'>Filter: </div>").append(filterSelect).insertAfter(checkResLink);

		checkButtons.prepend('<a name="region-' + list.attr('id') + '"></a>');
		list.before(checkButtons);
	});	
} // function hookupRegionActions()

function hookupLocationLinks(locations) {
	// Set as desination business.
	$("ul.list li").hover(
		function() {
			// We don't want to readd the link if we've already succeeded and faded out, but haven't done a mouseout yet.
			if (!($(this).hasClass("succeeded"))) {
				var url = $(this).find("a")[0].attributes["href"].value; // url to POST to

				// We also don't want to add a link if we've already got a link or a link that's been clicked!
				if ($(this).find(".noRemove").length == 0) {
					$(this).find(".after").append("<span id='destination'> &#8212; <span>Set as destination</span></span>");
					$(this).find("#destination span").css({"cursor": "pointer", "color": "#005C73", "font-weight": "bold"});
					$(this).find("#destination span").click(function() {
						// When clicked, say it's loading and submit the POST.
						var link = $(this);
						link.unbind("click");
						link.addClass("noRemove");
						link.html("Loading...");
						link.css({"cursor": "progress"});
						$.ajax({
							type: "POST",
							url: url,
							data: {set_as_destination: 1},
							success: function() {
								link.html("Success!");
								link.css({"cursor": "default", "color": "green"});
								link.parent().parent().parent().addClass("succeeded");
								link.parent().delay(500).fadeOut(function(){ $(this).remove(); });
							},
							error: function() {
								link.html("Error!");
								link.css({"cursor": "default", "color": "red"});
								link.parent().parent().parent().addClass("succeeded");
								link.parent().delay(500).fadeOut(function(){ $(this).remove(); });
							}
						});
					});
				}
			}
		},
		function() {
			// Remove the link only when it's a link, and not "Loading" or something.
			if ($(this).find(".noRemove").length == 0) {
				$(this).find("#destination").remove();
				$(this).removeClass("succeeded");
			}
		}
	);

	// Start the check.
	$("ul.list a").each(function(index, element) {
		var link = $(this);
		link.attr("target", "_blank");	// open up location pages in new tab to avoid accidental clicks
	});		
}	// function hookupLocationLinks(locations)


function scrapePage(params) {
	var href = params[0];
	var link = params[1];
	var btn = params[2];
	$.get(href, function(data) {
		scraped++;
		scrapeCount--;
		btn.html("Checking... " + scraped + " of " + total);
		var page = $(data);
		var visits = page.find('.section.label-section h3:contains("Visits")').parent();			
		// Bold if the street is unvisited, gray out if it has been visited.
		if(visits.html() == null) {
			//[TODO] handle scrapePage error?
		} else if (visits.html().match(/never been here before/)) {
			link.addClass('unvisited');
		} else {
			link.addClass('visited');
		}
		
		if (scrapeCount == 0) {
			btn.html('Check Visits');
			btn.removeClass('disabledButton');
			$('.checkVisit, .checkRes').removeAttr('disabled');
		}
	});	// $.get
}	// function scrapePage(link)

function getStreetInfo(params) {
	var tsid = params[0] + '';
	var link = params[1];		
	var appendage = params[2];
	var index = params[3];
	var btn = params[4];
	var region = params[5];

	api_call('locations.streetInfo', { street_tsid: tsid }, function(r) {
		checked++;
		checkCount--;
		btn.html("Checking... " + checked + " of " + total);

		if (!r.ok) {
			console.log('Error calling api for ' + tsid + ': ' + r.error);
			if (!window.DEBUG) { link.parent().remove(); } else { appendage.append(' &#8212; <span style="color:red;font-weight: bold">404!</span>'); }
			link.parent().addClass('hamsters');
			if (window.DEBUG) { appendage.append(' &#8212; <span style="color:red;font-weight: bold">ERR: ' + r.error + '</span>'); }
			return;
		}
		var activeProjects = r.active_project;
		// Add a note if there's an active project.
		if (activeProjects) {
			appendage.append(' &#8212; <span style="color:green;font-weight: bold">Active Project!</span>')
			link.parent().addClass("project");
		}

		// Pull the resource information.
		var info = r.features;
		$.each(info, function(index, feature) {
			switch(feature.substr(0, 4)) {
				case "A sh":
				case "A Sh":
					var god = $('<span>' + feature + '</span>').find("b").text();
					if(god == "Ti") {
						god = "Tii";
					}
					link.parent().addClass(god);
					if($("#" + god + "-" + region).length == 0) {
						var newItem = $("<option value='" + god + "' id='" + god + "-" + region + "'>" + god + "</option>")
						var added = false;
						$("#shrines-" + region + " option").each(function(index) {
							if ($(this).text() > god) {
								newItem.insertBefore($(this));
								added = true;
								return false;
							}
						});
						if(!added) {
							newItem.appendTo("#shrines" + "-" + region);
						}
					}
					break;
				default:
					$('<span>' + feature + '</span>').find("b").each(function() {
						var kind = "resources";
						var re = $(this).text().match(/([0-9]+ |A |An )?(.*)/);
						var resource = re[2];
						var quantity = re[1];
						if(resource.substr(-11) == " for mining") {
							resource = resource.substr(0, (resource.length - 11));
						} else if(resource.substr(-7) == " Vendor") {
							resource = resource.substr(0, (resource.length - 7));
							kind = "vendors";
						}
						var id = resource.substr(0,3);
						if(id == "Hou") {
							return;
						}
						if(quantity) {
							quantity = quantity.substr(0, (re[1].length -1));
							if(quantity.match(/[0-9]+/)) {
								link.attr(id, quantity);
							}
						}

						link.parent().addClass(id);
						if($("#" + id + "-" + region).length == 0) {
							var newItem = $("<option value='" + id + "' id='" + id + "-" + region + "'>" + resource + "</option>");
							var added = false;
							$("#" + kind + "-" + region + " option").each(function(index) {
								if ($(this).text() > resource) {
									newItem.insertBefore($(this));
									added = true;
									return false;
								}
							});
							if(!added) {
								newItem.appendTo("#" + kind + "-" + region);
							}
						} else {
							if($("#" + id + "-" + region).text().length < resource.length) {
								$("#" + id + "-" + region).text(resource);
							}
						}
					});
					break;
			}
		});

		// Enable filter drop down once done
		if(checkCount == 0) {
			btn.html('Check Resources');
			btn.removeClass('disabledButton');
			$('.checkVisit, .checkRes').removeAttr('disabled');
			$("#filter" + "-" + region + " select").removeAttr("disabled");
		}
	});	// api_call('locations.streetInfo');
} // function getStreetInfo(params)

// ----------------------------------------------
})();